using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Web.Util;
using SHDocVw;
using MSAAWrapper;

namespace webSurf
{
    public partial class Form1 : Form
    {
        System.Collections.Generic.Dictionary<int, string> urlList = new Dictionary<int, string>();
        System.Collections.Generic.List<string> fullNames = new List<string>();
        public Form1()
        {
            InitializeComponent();
        }
        private void GetHTML_Click(object sender, EventArgs e)
        {
            string url = "";
            if (comboBox1.SelectedIndex >= 0)
            {
                url = urlList[comboBox1.SelectedIndex];
            }
            else if (comboBox1.Text != "" && System.Uri.IsWellFormedUriString(comboBox1.Text, System.UriKind.Absolute))
            {
                url = comboBox1.Text;
            }
            else
            {
                MessageBox.Show("None selected item");
                return;
            }
            HttpWebRequest HttpWReq =
            (HttpWebRequest)WebRequest.Create(url); //

            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            System.IO.Stream hrd = HttpWResp.GetResponseStream();
            byte[] buff = new byte[20000];
            int num = 0;
            int lido = 0;
            do
            {
                num = hrd.ReadByte();// Read(buff, lido, buff.Length - 1);
                buff[lido] = (byte)num;
                lido += 1;
            } while (num > 0 && lido < buff.Length);
            System.Text.ASCIIEncoding ascii = new ASCIIEncoding();
            string texto = ascii.GetString(buff, 0, lido);  
                
            //", "http://192.168.100.1/RgConnect.asp", "");
//            string find = "&nbsp;Upstream Power</td> \
//               <td class="td">&nbsp;47.0 dBmV</td>\
//";
            MessageBox.Show("Veio " + lido.ToString() + " -- " + texto + " -- " );
            System.Windows.Forms.Clipboard.SetText(texto);
            wb1.DocumentText = texto;

        }
        /// <summary>
        /// look at getting a current IE instance in "http://www.codeguru.com/Cpp/I-N/ieprogram/article.php/c4403"
        /// looking into MSDN "http://msdn2.microsoft.com/en-us/library/aa770041.aspx"
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
 
        private void btIE_Click(object sender, EventArgs e)
        {
            object wref = new object [] { this };
            SHDocVw.ShellWindowsClass shw = new SHDocVw.ShellWindowsClass();
            Cursor bakCursor = this.Cursor;
            this.Cursor = Cursors.WaitCursor;
            int resu = 0;
            shw.FindWindowSW(ref wref,  ref wref, 1,  out  resu, 5);
           
            int ix = 0;
            SHDocVw.IWebBrowser  ie = null;
            comboBox1.Items.Clear();
            urlList.Clear();
            int HWND=0;
            foreach( object iq in shw)
            {
                if (iq != null )
                {
                    try
                    {
                        ie = (SHDocVw.WebBrowser_V1)iq;
                        string url = ie.LocationURL;
                        //;;; The inteface WebBrowser has HWND and others
                        SHDocVw.IWebBrowser2 ie2 = (SHDocVw.IWebBrowser2)iq;
                        SHDocVw.IWebBrowser ie0 = (SHDocVw.IWebBrowser )iq;
                        mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)ie0.Document;

                        string verbose = ie2.FullName;// ie.LocationName + " - " + ((!ie.TopLevelContainer)? (ie.Parent as SHDocVw.WebBrowser_V1).LocationURL:"");
                        //mshtml.IHTMLDocument iedoc = (mshtml.IHTMLDocument)ie.Document;
                        
                        if(verbose.Substring(verbose.LastIndexOf('\\')).ToLower() == "\\explorer.exe")
                            comboBox1.Items.Add("exp | " + ie.LocationName);
                        else
                            comboBox1.Items.Add("iex | " + ie.LocationName);
                        string kind = "";
                        HWND = 0;
                        try
                        {
                            kind = ie2.Type; // IWebBrowser_Type
                        }
                        catch (Exception eex)
                        {
                            System.Diagnostics.Trace.WriteLine("Invalid type; " + eex.Message);
                        }
                        try
                        {
                            HWND = ie2.HWND;
                        }
                        catch (Exception eex)
                        {
                            System.Diagnostics.Trace.WriteLine("HWND err: " + eex.Message);
                        }
                        IEnut nut = new IEnut("exp", ie.LocationName, url, HWND, iq);
                        comboBox1.Items.Add(nut);
                        urlList.Add(ix++, url);
                        fullNames.Add(verbose);
                        //ie2.Visible = true;
                        verbose += "\nname -" + ie2.Name;
                        verbose += "\nHWND = " + HWND.ToString("X");
                        verbose += "\nurl -" + ie.LocationURL;
                        verbose += "\nType -" + kind;
                        System.Diagnostics.Trace.WriteLine("VEIO:" + verbose);
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.WriteLine("Exep: " + ex.Message);
                        MessageBox.Show(ex.Message);
                    }
                }
            }
            if (comboBox1.Items.Count > 0)
                comboBox1.SelectedIndex = 0;
            this.Cursor = bakCursor;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btClipboard_Click(object sender, EventArgs e)
        {
            string urls = "";
            for (int ix = 0; ix < urlList.Count; ix++)
            {
                urls += "title=" + comboBox1.Items[ix] + "\r\n";
                urls += "explorer.exe /i,\"" + urlList[ix] + "\"\r\n\r\n";
            }
            MessageBox.Show("Urls=" + urls);
            Clipboard.SetText(urls);
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            string urls = "Veio: ";// +(fullNames.Count > 0 ? fullNames[comboBox1.SelectedIndex] : "");
            if (comboBox1.SelectedItem.GetType() == typeof(IEnut))
            {
                urls = comboBox1.SelectedItem.ToString();
                IWebBrowser2 ie = (IWebBrowser2) ((IEnut)comboBox1.SelectedItem).IDdisp;
                urls += "<br>" + ie.LocationURL;
                if (ie.Document.GetType() == typeof(mshtml.HTMLDocumentClass))
                {
                    mshtml.HTMLDocumentClass doc = (mshtml.HTMLDocumentClass)ie.Document;
                    urls += "<br>" + doc.IHTMLDocument2_body.outerText ;
                }
            }
            wb1.DocumentText = urls;
        }

        private void brLoadTxt_Click(object sender, EventArgs e)
        {
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.DefaultExt = "txt";
            openFileDialog1.InitialDirectory = "c:/";
            DialogResult dres = openFileDialog1.ShowDialog(this);
            if(dres == DialogResult.OK)
                readTxt(openFileDialog1.FileName);

        }
        private void readTxt(string fileName)
        {
            //MessageBox.Show("Veio " + fileName);
            System.Collections.Generic.List<string> urls = new List<string>();
            System.IO.StreamReader trd = new System.IO.StreamReader(fileName);
            if (true)
            {
                string txRead = "";
                while (!trd.EndOfStream)
                {
                    string line = trd.ReadLine();
                    string [] lineInfo = line.Split('|');
                    urls.Add(lineInfo[1]);
                    iniBrowse(lineInfo[1], lineInfo[0]);
                    txRead += line;
                }
                trd.Close();
            }
            //object wref = new object[] { this };
            //SHDocVw.WebBrowserClass webb = new SHDocVw.WebBrowserClass();
            //SHDocVw.ShellWindowsClass shw = new SHDocVw.ShellWindowsClass();
            //SHDocVw.ShellBrowserWindow web = (SHDocVw.ShellBrowserWindow)webb;
            //web.Visible = true;
            Cursor bakCursor = this.Cursor;
            //webb.Visible = true;
            //object obj =new  object []{ null };
            //webb.Navigate("http://www.msn.com.br", ref obj, ref obj, ref obj, ref obj);

            

        }
        /// <summary>
        /// Kind defines the explorer to start
        /// 1 means iexplorer
        /// </summary>
        /// <param name="s_url"></param>
        /// <param name="kind"></param>
        private void iniBrowse(string s_url, string kind)
        {
            string m_navigator = kind == "exp" ? "explorer.exe" : "iexplore.exe";
            System.Diagnostics.Process procs = null;
            System.Diagnostics.ProcessStartInfo spawn = new System.Diagnostics.ProcessStartInfo( m_navigator, "/i, \"" + s_url + "\"");
			spawn.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            try
            {
                procs = System.Diagnostics.Process.Start(spawn);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Erro: " + ex.Message);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            string uuu = System.Web.HttpUtility.HtmlEncode("<aaaaaaaaaa>");
            string s_url = "http://www.uol.com.br"; //"http://technet.microsoft.com/en-us/library/bb491071.aspx";
            string m_navigator = "explorer.exe";
            System.Diagnostics.Process procs = null;
            System.Diagnostics.ProcessStartInfo spawn = new System.Diagnostics.ProcessStartInfo(m_navigator, "" + s_url);
            spawn.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            for (int ctt = 0; ctt < 5; ctt++)
            {
                try
                {
                    procs = System.Diagnostics.Process.Start(spawn);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Erro: " + ex.Message);
                }
            }
        }

        private void btConvert_Click(object sender, EventArgs e)
        {

            string urll = MeuDecode(comboBox1.Text);
            comboBox1.Text = urll;    
        }
        private string MeuDecode(string txt)
        {
            string dtxt = txt;
            dtxt = txt.Replace("%3a", ":");
            dtxt = dtxt.Replace("%2f", "/");

            return dtxt;
        }

        private void btTest_Click(object sender, EventArgs e)
        {
            //
            //MessageBox.Show("SetCapture\nhttp://msdn.microsoft.com/en-us/library/aa927344.aspx");
            bool ueh = MSAAWrapper.NativeWin32.SetForegroundWindow(this.Handle);
            NativeWin32.LockSetForegroundWindow(MSAAWrapper.NativeWin32.LockSetCaptureValues.LSFW_LOCK);
            IntPtr retu = MSAAWrapper.NativeWin32.SetCapture(this.Handle);
            NativeWin32.WINDOWINFO pwi = new NativeWin32.WINDOWINFO();
            NativeWin32.GetWindowInfo(this.Handle, out pwi);
            //StringBuilder title = new StringBuilder(' ', 128);
            string title = new string(' ', 128);
            NativeWin32.GetWindowText(this.Handle, title, 128);
            this.Text = retu.ToString() + " -> " + (retu == this.Handle ? "=" : "!= , ueh=" + ueh.ToString());
        }


        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            //MSAAWrapper.NativeWin32.ReleaseCapture();
        }

        private void Form1_MouseMove(object sender, MouseEventArgs e)
        {
            this.Text = "X=" + MousePosition.X.ToString() + "; Y=" + MousePosition.Y.ToString() + " tp=" +
                    DateTime.Now.TimeOfDay.Milliseconds.ToString();
            Application.DoEvents();
            this.Update();
        }

        private void Form1_MouseCaptureChanged(object sender, EventArgs e)
        {
            //this.Text = "Captured!";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string url = "http://200.221.2.45";
            HttpWebRequest HttpWReq =
                        (HttpWebRequest)WebRequest.Create(url); //

            HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();
            System.IO.Stream hrd = HttpWResp.GetResponseStream();
            byte[] buff = new byte[20000];
            int num = 0;
            int lido = 0;
            do
            {
                num = hrd.ReadByte();// Read(buff, lido, buff.Length - 1);
                buff[lido] = (byte)num;
                lido += 1;
            } while (num > 0 && lido < buff.Length);
            System.Text.ASCIIEncoding ascii = new ASCIIEncoding();
            string texto = ascii.GetString(buff, 0, lido);  

        }

        private void button3_Click(object sender, EventArgs e)
        {
            frmFindW frm = new frmFindW();
            frm.Mae = this;
            this.WindowState = FormWindowState.Minimized;
            frm.ShowDialog(this);
        }

        private void btFinger_Click(object sender, EventArgs e)
        {
            frmFisher frm = new frmFisher();
            frm.Mae = this;
            this.WindowState = FormWindowState.Minimized;
            frm.ShowDialog(this);
        }


    }
}